<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/22
 * Time: 10:20
 */

namespace zhtfrontend\modules\cus\controllers;

use common\components\helpers\Fun;
use common\models\datas\CustomerFieldConfig;
use common\models\datas\CustomerFieldConfigRelation;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\modules\cus\components\services\Cusfc;


class CustomerfieldconfigController extends BaseController
{

    public function actionIndex()
    {
        $where = \Yii::$app->request->get();
        $page = isset($where['page']) ? $where['page'] : 0;
        $data = Cusfc::GetList($where, $page);
        return $this->render('index', ['data' => $data['data'], 'pages' => $data['pages']]);
    }

    //针对类型加以区分
    public function actionCreate()
    {
        $model = new CustomerFieldConfig();
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $data = Cusfc::doSave($model);
            return $this->redirectMessage($data['message'], Fun::url(['cus-customerfieldconfig-index']));
        }
        return $this->render('create', ['model' => $model]);
    }

    public function actionUpdate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $customer_field_config = CustomerFieldConfig::findOne($id);
        $model = CustomerFieldConfigRelation::findOne(['customer_field_config_id'=>$id,'site_id'=>Fun::getSiteId()]);
        if(empty($model)){
            $model = new CustomerFieldConfigRelation();
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->customer_field_config_id = $customer_field_config->id;
            $model->site_id = Fun::getSiteId();
            $model->module = $customer_field_config->module;
            if ($model->save(false)) {
                return $this->redirectMessage('设置成功', Fun::url(['cus-customerfieldconfig-index']));
            }
        }
        return $this->render('update', ['model' => $model]);
    }

}
